package com.future.mayi.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.DateUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.ToastUtil;
import com.future.baselib.utils.ToastUtils;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.utils.imageselectcache.CacheManager;
import com.future.mayi.utils.perimission.DefaultRationale;
import com.future.mayi.utils.perimission.PermissionSetting;
import com.imnjh.imagepicker.util.FileUtil;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class MyQrCodeActivity extends BaseTitleActivity {
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;
    @BindView(R.id.tv_save)
    TextView tvSave;

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("推广二维码");
        getRightText().setText("换个样式");
        getRightText().setTextColor(getResources().getColor(R.color.text_colorfe7712));
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_my_qr_code);
    }

    @Override
    protected void initView() {
        ViewGroup.LayoutParams layoutParams;
        float width = CommonUtils.getScreenSize(mContext)[0] - CommonUtils.dip2px(mContext, 34.0f * 2);
        float height = width / 750.0f * 1137.0f;
        if (ivQrCode.getLayoutParams() == null) {
            layoutParams = new ViewGroup.LayoutParams((int) width, (int) height);
        } else {
            layoutParams = ivQrCode.getLayoutParams();
            layoutParams.height = (int) height;
        }
        ivQrCode.setLayoutParams(layoutParams);
    }

    @Override
    protected void initDates() {
        getQrCode(false);
    }

    @Override
    protected void initListener() {
        getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getQrCode(true);
            }
        });
    }

    private String qrcode_img = "";

    private void getQrCode(boolean change) {
        setEnabled(false);
        new HttpRequest<DefaultResponse>()
                .with(getActivity())
                .addParam("token", App.getToken(mContext))
                .setApiCode(change ? ApiCst.changeQrcode : ApiCst.getQrcode)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        try {
                            JSONObject object = new JSONObject(response.content);
                            qrcode_img = object.optString("qrcode_img");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        loadImg(ivQrCode, qrcode_img);
                        setEnabled(true);
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                        setEnabled(true);
                    }
                })
                .start(new DefaultResponse());
    }

    private void setEnabled(boolean enabled) {
        if (enabled) {
            dissmissLoadingDialog();
        } else {
            showLoadingDialog();
        }
        getRightText().setEnabled(enabled);
        tvSave.setEnabled(enabled);
    }


    @OnClick({R.id.tv_wechatmoments, R.id.tv_wechat, R.id.tv_save})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_wechatmoments:
                setEnabled(false);
                save(1);
                break;
            case R.id.tv_wechat:
                setEnabled(false);
                save(2);
                break;
            case R.id.tv_save:
                setEnabled(false);
                save(0);
                break;
        }
    }


    private DefaultRationale mRationale;
    private PermissionSetting mSetting;

    private void save(final int shareType) {
        if (TextUtils.isEmpty(qrcode_img)) {
            setEnabled(true);
            return;
        }
        if (mRationale == null) {
            mRationale = new DefaultRationale();
        }
        if (mSetting == null) {
            mSetting = new PermissionSetting(this);
        }
        AndPermission.with(this)
                .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .rationale(mRationale)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        download(shareType);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(MyQrCodeActivity.this, permissions)) {
                            mSetting.showSetting(permissions);
                        } else {
                            setEnabled(true);
                        }
                    }
                })
                .start();
    }


    private void download(final int shareType) {
        Glide.with(mContext)
                .load(qrcode_img)
                .asBitmap()
                .toBytes()
                .into(new SimpleTarget<byte[]>() {
                    @Override
                    public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                        // 下载成功回调函数
                        // 数据处理方法，保存bytes到文件
                        copy(shareType, bytes);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setEnabled(true);
                            }
                        });
                    }
                });
    }

    private boolean success;

    /**
     * 复制文件
     *
     * @param bytes 数据
     */
    private void copy(final int shareType, byte[] bytes) {
        success = true;
        String filePath = null;
        try {
            String fileName = "qr_code_" + DateUtils.getDateYMDHMS2() + ".jpg";
            filePath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator;
            if (new File(filePath+ "Camera" + File.separator).exists()) {
                filePath = filePath + "Camera" + File.separator;
            }
            File file = new File(filePath, fileName);
            FileOutputStream outStream = new FileOutputStream(file.toString());
            outStream.write(bytes);
            outStream.close();
            filePath = file.getPath();
            //MediaStore.Images.Media.insertImage(getContentResolver(), filePath, fileName, null);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(file));
            sendBroadcast(intent);
        } catch (IOException e) {
            success = false;
            ToastUtils.longToast(this, "图片保存失败:" + e.getMessage());
            e.printStackTrace();
        } finally {
            final String finalFilePath = filePath;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!success) {
                        toast("图片保存失败");
                        setEnabled(true);
                        return;
                    }

                    if (shareType == 0) {
                        toast("图片保存成功");
                        setEnabled(true);
                    } else {
                        share(shareType, finalFilePath);
                    }
                }
            });

        }
    }


    private void share(final int shareType, String filePath) {
        Platform.ShareParams sp = new Platform.ShareParams();
        if (shareType == 2) {
            sp.setShareType(Platform.SHARE_IMAGE);
            sp.setImagePath(filePath);
            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
            wechat.setPlatformActionListener(platformActionListener);
            wechat.share(sp);
        } else if (shareType == 1) {
            sp.setShareType(Platform.SHARE_IMAGE);
            sp.setImagePath(filePath);
            Platform monments = ShareSDK.getPlatform(WechatMoments.NAME);
            monments.setPlatformActionListener(platformActionListener);
            monments.share(sp);
        }
    }


    // 设置分享事件回调
    PlatformActionListener platformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setEnabled(true);
                }
            });
        }


        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setEnabled(true);
                }
            });
        }

        @Override
        public void onCancel(Platform platform, int i) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setEnabled(true);
                }
            });
        }
    };


}
